package com.cfswt.tasksystem.exception;

import com.cfswt.tasksystem.response.JsonResult;
import com.cfswt.tasksystem.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalHandlerException {
    /**
     * 校验参数校验异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doIllegalArgumentException(IllegalArgumentException e) {
        log.warn("IllegalArgumentException msg is {}", e.getMessage());
        return new JsonResult(StatusCode.VALIDATE_ERROR, e.getMessage());
    }

    /**
     * 校验运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public JsonResult doRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.warn("RuntimeException msg is {}", e.getMessage());
        log.info("Request details - URI: {}, Method: {}", request.getRequestURI(), request.getMethod());
        return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
    }

    /**
     * 拦截SpringSecurity校验用户名不存在时,抛出异常
     */
    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public JsonResult doInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        log.warn("InternalAuthenticationServiceException msg is {}", e.getMessage());
        return new JsonResult(StatusCode.USERNAME_ERROR, e.getMessage());
    }
    /**
     * 拦截SpringSecurity校验密码不匹配时,抛出异常
     */
    @ExceptionHandler(BadCredentialsException.class)
    public JsonResult doBadCredentialsException(BadCredentialsException e) {
        log.warn("BadCredentialsException msg is{}", e.getMessage());
        return new JsonResult(StatusCode.PASSWORD_ERROR, e.getMessage());
    }
}
